import React, { useEffect, useState } from 'react'
import axios from '../../api/index'
import { useNavigate, useSearchParams } from 'react-router-dom'
import { IndexBar, List ,Grid, SearchBar, Button } from 'antd-mobile'
import { LocationFill } from 'antd-mobile-icons'
import { useDispatch } from 'react-redux'
import { getEnd, getStart } from '../../store/home'
function index() {
  const [list,setList]=useState([])
  const [ss,setSs]=useState([])
  const [dq,setDq]=useState([])
  const [dqs,setDqs]=useState(false)
  const [search]=useSearchParams()
  const type=search.get('type')
  const  [lsjl,setLsjl]=useState(
    JSON.parse(localStorage.getItem('lsjl')) || []
  )
  useEffect(()=>{
    localStorage.setItem('lsjl',JSON.stringify(lsjl))
  },[lsjl])
  const getData = async () => {
    const res = await axios.get('/city')
    setList(res.data.data)
    const resp=await axios.get('/city/location',{params:{key:'09367722776aa3ebf9a578447b7fa5d8'}})
    setDq(resp.data.data)
  }
  useEffect(()=>{
    getData()
  },[])
  const onSearch=(val)=>{
    setLsjl(lsjl.concat(val))
    axios.get('/city/search',{params:{kw:val}}).then(res=>{
      setSs(res.data.data)
    })
    setDqs(true)
  }
  const nav=useNavigate()
  const dispatch=useDispatch()
  const dian=(item)=>{
    if(type==='start'){
      dispatch(getStart(item))
    }else{
      dispatch(getEnd(item))
    }
    nav(-1)
  }
  return (
    <div>
      <SearchBar placeholder="请输入城市名" onSearch={onSearch} onClear={()=>setDqs(false)}/> 
      {
        dqs?<List>
          {
            ss.map((item,index)=>{
              return <List.Item key={index} onClick={()=>dian(item.name)}>{item.name}</List.Item>
            })
          }
        </List>:<> 
       
        <div>
        <LocationFill />
        {dq.province}
      </div> 
      <div>
          {
            lsjl.map((item,index)=>{
              return <div key={index} onClick={()=>dian(item)}>{item}</div>
            })
          }
          <Button onClick={()=>setLsjl([])}>清除全部</Button>
        </div>
      <Grid columns={3} gap={8} style={{marginLeft:'50px'}}>
        {
          list.hotCities?.map((item, index) => {
            return <Grid.Item  key={index} onClick={()=>dian(item.name)}>{item.name}</Grid.Item >
          })
        }
      </Grid >
       <div style={{ height: '85vh' }}>
      <IndexBar>
        {list.cityList?.map(group => {
          const { title, items } = group
          return (
            <IndexBar.Panel
              index={title}
              title={`标题${title}`}
              key={`标题${title}`}
            >
              <List>
                {items?.map((item, index) => (
                  <List.Item key={index} onClick={()=>dian(item.name)}>{item.name}</List.Item>
                ))}
              </List>
            </IndexBar.Panel>
          )
        })}
      </IndexBar>
      </div></>
      }
    </div>
  )
}

export default index